import { CommandContext } from '../interfaces/command-context.interface'
import { MessageContent } from 'discordoo'
import { Command } from '../interfaces/command.interface'
import { inspect } from 'util'

export class EvalCommand implements Command {
  public readonly name = 'eval'
  public readonly ownersOnly = true

  async handle(ctx: CommandContext): Promise<MessageContent> {
    const code = ctx.args.slice(1).join(' ')
    let result: any, more = false

    const before = process.hrtime.bigint()
    try {
      // we will be able to use eval() with code blocks in the message
      let content = code.replace(/```(.+)?/g, '')

      // more flag means that we need to display more details in the result
      content = content.replace('--more', () => {
        more = true
        return ''
      })

      result = await eval(content)
    } catch (e) {
      result = e
    }
    const after = process.hrtime.bigint()

    // replace bot token to prevent people from seeing it in the result
    const tokenRegExp = new RegExp(`${ctx.message.client.token}`
      .replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')

    result = typeof result === 'string' ? result : inspect(result, { depth: more ? 1 : 0 })
    result = result.replace(tokenRegExp, '__token').replace(/```/g, '`\u200b``')
    result = 'Completed in '
      + (after - before) +
      ' nanoseconds or ' + (parseInt(String(after - before)) / 1000000).toFixed(3) + 'ms\n'
      + result
    result = result.slice(0, 1980)
    result = '```js\n' + result + '\n```'

    return result
  }
}
